<template>
  <div class="doc-detail-container">
    <div class="detail-layout">
      <!-- 左侧边栏 -->
      <div class="sidebar-section">
        <div class="sidebar-content">
          <!-- 侧边栏头部 -->
          <div class="sidebar-header">
            <div class="header-icon">
              <svg
                t="1721703357297"
                class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
              >
                <path
                  d="M184.797556 1023.984039a107.051063 107.051063 0 0 1-77.235738-33.518299A111.440364 111.440364 0 0 1 73.069892 909.782405V63.844379a63.844379 63.844379 0 0 1 63.844379-63.844379h750.171458a63.844379 63.844379 0 0 1 63.844379 63.844379v960.155621zM136.914271 816.777106v86.349523a50.022071 50.022071 0 0 0 47.883285 51.809714h702.288173v-189.937029H184.797556a50.00611 50.00611 0 0 0-47.883285 51.777792z m448.043893-304.856911A46.781969 46.781969 0 0 0 631.708211 558.638319h175.572043a46.781969 46.781969 0 0 0 46.734086-46.734086A46.79793 46.79793 0 0 0 807.280254 465.154187H631.708211a46.79793 46.79793 0 0 0-46.750047 46.750046z m0-207.494233A46.781969 46.781969 0 0 0 631.708211 351.144086h175.572043a46.781969 46.781969 0 0 0 46.734086-46.734085A46.79793 46.79793 0 0 0 807.280254 257.659954H631.708211a46.79793 46.79793 0 0 0-46.750047 46.766008z"
                  fill="#347ED5"
                ></path>
              </svg>
            </div>
            <h3 class="sidebar-title" @click="activeId = null">{{ nameTitle }}</h3>
          </div>

          <!-- 搜索框 -->
          <div class="search-section">
            <el-input
              v-model="sidebarInputValue"
              placeholder="搜索文档..."
              @input="keywordChange"
              class="search-input"
            >
              <template #prefix>
                <Icon icon="ep:search" />
              </template>
            </el-input>
          </div>

          <!-- 文档列表 -->
          <div class="docs-list-section">
            <el-scrollbar class="docs-scrollbar">
              <div v-if="filterList.length > 0" class="docs-list">
                <div
                  v-for="item in filterList"
                  :key="item.id"
                  @click="handleActiveId(item.id)"
                  class="doc-item"
                  :class="{ 'doc-active': activeId == item.id }"
                >
                  <div class="doc-icon">
                    <Icon icon="ep:document" />
                  </div>
                  <div class="doc-info">
                    <span class="doc-name">{{ item.name }}</span>
                    <span class="doc-time">{{ formatDate(item.createTime) }}</span>
                  </div>
                </div>
              </div>
              <div v-else class="empty-docs">
                <div class="empty-icon">
                  <Icon icon="ep:document-copy" />
                </div>
                <p class="empty-text">没有找到相关文档</p>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="main-content">
        <div class="content-wrapper">
          <!-- 未选择文档时的状态 -->
          <div v-if="activeId == null" class="no-doc-selected">
            <!-- 头部操作栏 -->
            <div class="content-header">
              <div class="header-left">
                <div class="knowledge-icon">
                  <svg
                    t="1721703357297"
                    class="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    width="32"
                    height="32"
                  >
                    <path
                      d="M184.797556 1023.984039a107.051063 107.051063 0 0 1-77.235738-33.518299A111.440364 111.440364 0 0 1 73.069892 909.782405V63.844379a63.844379 63.844379 0 0 1 63.844379-63.844379h750.171458a63.844379 63.844379 0 0 1 63.844379 63.844379v960.155621zM136.914271 816.777106v86.349523a50.022071 50.022071 0 0 0 47.883285 51.809714h702.288173v-189.937029H184.797556a50.00611 50.00611 0 0 0-47.883285 51.777792z m448.043893-304.856911A46.781969 46.781969 0 0 0 631.708211 558.638319h175.572043a46.781969 46.781969 0 0 0 46.734086-46.734086A46.79793 46.79793 0 0 0 807.280254 465.154187H631.708211a46.79793 46.79793 0 0 0-46.750047 46.750046z m0-207.494233A46.781969 46.781969 0 0 0 631.708211 351.144086h175.572043a46.781969 46.781969 0 0 0 46.734086-46.734085A46.79793 46.79793 0 0 0 807.280254 257.659954H631.708211a46.79793 46.79793 0 0 0-46.750047 46.766008z"
                      fill="#347ED5"
                    ></path>
                  </svg>
                </div>
                <h2 class="knowledge-title">{{ nameTitle }}</h2>
              </div>
              <div class="header-actions">
                <el-button
                  v-hasPermi="['system:docs:create']"
                  type="primary"
                  @click="handleOpenDocForm('create')"
                  class="create-doc-btn"
                >
                  <Icon icon="ep:plus" class="btn-icon" />
                  新建文档
                </el-button>
                <el-dropdown
                  trigger="click"
                  placement="bottom-end"
                  v-hasPermi="['system:docs:update', 'system:docs:delete']"
                >
                  <el-button class="more-btn">
                    <Icon icon="ep:more-filled" />
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu class="action-menu">
                      <el-dropdown-item
                        @click="openGroupForm('update', docGroupId)"
                        v-hasPermi="['system:docs:update']"
                        class="menu-item edit-item"
                      >
                        <Icon icon="ep:edit" class="menu-icon" />
                        <span>编辑知识库</span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click="delGroup(docGroupId)"
                        v-hasPermi="['system:docs:delete']"
                        class="menu-item delete-item"
                      >
                        <Icon icon="ep:delete" class="menu-icon" />
                        <span>删除知识库</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>

            <!-- 文档列表展示 -->
            <div class="docs-overview">
              <div v-if="filterList.length > 0" class="docs-grid">
                <div
                  v-for="item in filterList"
                  :key="item.id"
                  @click="handleActiveId(item.id)"
                  class="doc-card"
                >
                  <div class="card-icon">
                    <Icon icon="ep:document" />
                  </div>
                  <div class="card-content">
                    <h4 class="card-title">{{ item.name }}</h4>
                    <p class="card-time">{{ formatDate(item.createTime) }}</p>
                  </div>
                  <div class="card-arrow">
                    <Icon icon="ep:arrow-right" />
                  </div>
                </div>
              </div>
              <div v-else class="empty-overview">
                <div class="empty-illustration">
                  <Icon icon="ep:document-add" class="empty-main-icon" />
                </div>
                <h3 class="empty-title">此知识库暂无文档</h3>
                <p class="empty-description">创建您的第一个文档，开始记录知识</p>
                <el-button
                  type="primary"
                  @click="handleOpenDocForm('create')"
                  class="create-first-doc-btn"
                >
                  <Icon icon="ep:plus" class="btn-icon" />
                  创建文档
                </el-button>
              </div>
            </div>
          </div>

          <!-- 选中文档时的详情显示 -->
          <div v-else class="doc-detail">
            <!-- 文档头部 -->
            <div class="doc-header">
              <div class="doc-title-section">
                <h1 class="doc-title">{{ docData.name }}</h1>
              </div>
              <div class="doc-actions">
                <el-button
                  type="success"
                  v-hasPermi="['system:docs:update']"
                  @click="handleOpenDocForm('update', docData.id)"
                  class="edit-doc-btn"
                >
                  <Icon icon="ep:edit" class="btn-icon" />
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  v-hasPermi="['system:docs:delete']"
                  @click="delDoc(docData.id)"
                  class="delete-doc-btn"
                >
                  <Icon icon="ep:delete" class="btn-icon" />
                  删除
                </el-button>
              </div>
            </div>

            <!-- 文档内容 -->
            <div class="doc-content">
              <el-scrollbar class="content-scrollbar">
                <div class="content-body" v-html="docData.content" @click="handleImageClick"></div>
              </el-scrollbar>
            </div>

            <!-- 文档底部信息 -->
            <div class="doc-footer">
              <div class="footer-info">
                <Icon icon="ep:clock" class="footer-icon" />
                <span class="footer-label">创建时间：</span>
                <span class="footer-value">{{ formatDate(docData.createTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 弹窗组件 -->
  <DocGroupForm ref="groupFormRef" @success="getList" />
  <DocsForm ref="formRef" @success="getList" />
  <el-image-viewer
    v-if="dialogVisible"
    @close="dialogVisible = false"
    hide-on-click-modal
    :url-list="htmlStringUrl"
  />
</template>

<script lang="ts" setup>
import { MoreFilled, Delete } from '@element-plus/icons-vue'
import * as DocsApi from '@/api/system/docs'
import { formatDate } from '@/utils/formatTime'
import DocsForm from './DocsForm.vue'
import DocGroupForm from './DocGroupForm.vue'
import * as DocGroupApi from '@/api/system/docgroup'
import { useTagsViewStore } from '@/store/modules/tagsView'

defineOptions({ name: 'InstructionsDetail' })

const message = useMessage()
const { t } = useI18n()
const htmlStringUrl = ref([])
const dialogVisible = ref(false)

const tagsViewStore = useTagsViewStore()
const visitedViews = computed(() => tagsViewStore.getVisitedViews)
const { push } = useRouter()

// 删除知识库
const delGroup = async (id: number) => {
  try {
    await message.delConfirm('此操作将永久删除该知识库, 是否继续?')
    await DocGroupApi.deleteDocGroup(id)
    const view = visitedViews.value.find((i) => i.title === '文档中心详情')
    tagsViewStore.delView(view)
    push('/user/instructions')
  } catch {}
}

// 添加/修改知识库操作
const groupFormRef = ref()
const openGroupForm = (type: string, id?: number) => {
  groupFormRef.value.open(type, id)
}

// 筛选文档
const sidebarInputValue = ref('')
const list = ref([])
const nameTitle = ref('')
const docGroupId = ref(null)
const route = useRoute()

// 初始化
onMounted(() => {
  docGroupId.value = route.query.id
  nameTitle.value = route.query.name
  if ('hasDocId' in route.query) {
    handleActiveId(route.query.hasDocId)
  }
  if (docGroupId.value) {
    DocsApi.getDocsPage({
      groupId: docGroupId.value
    }).then((res) => {
      list.value = res.list
      keywordChange()
    })
  }
})

// 预览图片
const handleImageClick = (event) => {
  const target = event.target
  if (target.tagName === 'IMG') {
    htmlStringUrl.value = [target.src]
    dialogVisible.value = true
  }
}

// 获取文档列表
const getList = async (id) => {
  const data = await DocsApi.getDocsPage({
    groupId: docGroupId.value
  })
  list.value = data.list
  keywordChange()
  if (id) {
    handleActiveId(id)
  }
}

const filterList = ref([])
const keywordChange = () => {
  filterList.value = seachArray(list.value, sidebarInputValue.value)
}

const seachArray = (arr, keyword) => {
  const newArr = arr.filter((item) => {
    return item.name.toUpperCase().includes(keyword.toUpperCase())
  })
  return newArr
}

// 当前被选中的文档
const activeId = ref(null)
const docData = ref({})
const handleActiveId = async (id) => {
  activeId.value = id
  const data = await DocsApi.getDocs(id)
  docData.value = data
}

// 新增、编辑文档
const formRef = ref()
const handleOpenDocForm = (type: string, id?: number) => {
  formRef.value.open(type, docGroupId.value, id)
}

// 删除文档
const delDoc = async (id: number) => {
  try {
    await message.delConfirm()
    await DocsApi.deleteDocs(id)
    message.success(t('common.delSuccess'))
    await getList()
    activeId.value = null
  } catch {}
}
</script>

<style scoped lang="scss">
.doc-detail-container {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
  padding: 20px;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.detail-layout {
  display: flex;
  height: 100%;
  gap: 20px;
}

/* 左侧边栏 */
.sidebar-section {
  width: 300px;
  flex-shrink: 0;
}

.sidebar-content {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
}

.sidebar-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 20px;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
  background: linear-gradient(135deg, rgba(0, 82, 204, 0.02) 0%, transparent 100%);
}

.header-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border-radius: 10px;
  color: white;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  cursor: pointer;
  transition: color 0.2s ease;

  &:hover {
    color: #0052cc;
  }
}

.search-section {
  padding: 16px 20px;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
}

.search-input {
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }
}

.docs-list-section {
  flex: 1;
  overflow: hidden;
  padding: 16px 0;
}

.docs-scrollbar {
  height: 100%;
  padding: 0 20px;
}

.docs-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.doc-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;

  &:hover {
    background: rgba(0, 82, 204, 0.05);
    border-color: rgba(0, 82, 204, 0.2);
  }

  &.doc-active {
    background: linear-gradient(135deg, rgba(0, 82, 204, 0.1) 0%, rgba(0, 82, 204, 0.05) 100%);
    border-color: #0052cc;

    .doc-name {
      color: #0052cc;
      font-weight: 600;
    }
  }
}

.doc-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
  flex-shrink: 0;
}

.doc-info {
  flex: 1;
  min-width: 0;
}

.doc-name {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: color 0.2s ease;
}

.doc-time {
  font-size: 12px;
  color: #9ca3af;
}

.empty-docs {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
}

.empty-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #9ca3af;
  margin-bottom: 12px;
}

.empty-text {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

/* 主内容区 */
.main-content {
  flex: 1;
  overflow: hidden;
}

.content-wrapper {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  height: 100%;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
}

/* 未选择文档状态 */
.no-doc-selected {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
  background: linear-gradient(135deg, rgba(0, 82, 204, 0.02) 0%, transparent 100%);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.knowledge-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.knowledge-title {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.create-doc-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

.more-btn {
  border: 2px solid #e5e7eb;
  color: #6b7280;
  border-radius: 8px;

  &:hover {
    border-color: #0052cc;
    color: #0052cc;
  }
}

.action-menu {
  :deep(.el-dropdown-menu__item) {
    padding: 0;
  }
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  transition: all 0.2s ease;

  &.edit-item:hover {
    background: rgba(16, 185, 129, 0.1);
    color: #10b981;
  }

  &.delete-item:hover {
    background: rgba(239, 68, 68, 0.1);
    color: #ef4444;
  }
}

.menu-icon {
  font-size: 14px;
}

.docs-overview {
  flex: 1;
  padding: 24px;
  overflow: hidden;
}

.docs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  height: 100%;
  overflow-y: auto;
}

.doc-card {
  background: white;
  border: 1px solid rgba(0, 82, 204, 0.1);
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 16px;

  &:hover {
    border-color: #0052cc;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 82, 204, 0.15);
  }
}

.card-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  flex-shrink: 0;
}

.card-content {
  flex: 1;
  min-width: 0;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-time {
  font-size: 13px;
  color: #9ca3af;
  margin: 0;
}

.card-arrow {
  color: #9ca3af;
  font-size: 16px;
  transition: all 0.2s ease;
}

.doc-card:hover .card-arrow {
  color: #0052cc;
  transform: translateX(4px);
}

.empty-overview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

.empty-main-icon {
  font-size: 80px;
  color: #d1d5db;
  margin-bottom: 24px;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 8px 0;
}

.empty-description {
  font-size: 14px;
  color: #6b7280;
  margin: 0 0 24px 0;
}

.create-first-doc-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

/* 文档详情 */
.doc-detail {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.doc-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
  background: linear-gradient(135deg, rgba(0, 82, 204, 0.02) 0%, transparent 100%);
}

.doc-title {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin: 0;
}

.doc-actions {
  display: flex;
  gap: 12px;
}

.edit-doc-btn {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

.delete-doc-btn {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

.doc-content {
  flex: 1;
  overflow: hidden;
  padding: 0 24px;
}

.content-scrollbar {
  height: 100%;
}

.content-body {
  padding: 24px 0;
  line-height: 1.8;
  color: #374151;

  :deep(h1, h2, h3, h4, h5, h6) {
    color: #1f2937;
    margin-top: 24px;
    margin-bottom: 16px;
  }

  :deep(p) {
    margin-bottom: 16px;
  }

  :deep(img) {
    max-width: 100%;
    border-radius: 8px;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:hover {
      transform: scale(1.02);
    }
  }

  :deep(code) {
    background: rgba(0, 82, 204, 0.1);
    padding: 2px 6px;
    border-radius: 4px;
    font-family: 'Consolas', 'Monaco', monospace;
  }

  :deep(pre) {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 16px;
    overflow-x: auto;
  }
}

.doc-footer {
  padding: 16px 24px;
  border-top: 1px solid rgba(0, 82, 204, 0.1);
  background: rgba(0, 82, 204, 0.02);
}

.footer-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #6b7280;
}

.footer-icon {
  color: #0052cc;
}

.footer-label {
  font-weight: 500;
}

.footer-value {
  color: #374151;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .docs-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
}

@media (max-width: 768px) {
  .doc-detail-container {
    padding: 12px;
  }

  .detail-layout {
    flex-direction: column;
    gap: 12px;
  }

  .sidebar-section {
    width: 100%;
    height: 300px;
  }

  .docs-grid {
    grid-template-columns: 1fr;
  }

  .content-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .doc-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .doc-detail-container {
    background: linear-gradient(135deg, #1f2937 0%, #111827 100%);
  }

  .sidebar-content,
  .content-wrapper {
    background: rgba(30, 41, 59, 0.95);
  }

  .sidebar-title,
  .knowledge-title,
  .doc-title {
    color: #f9fafb;
  }

  .doc-name,
  .card-title {
    color: #e5e7eb;
  }

  .empty-title {
    color: #f9fafb;
  }

  .empty-description,
  .empty-text {
    color: #d1d5db;
  }
}
</style>
